package ru.spb.osll.myfit.server.handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.server.ImportsPrinter;
import ru.spb.osll.myfit.server.parser.PageUtils;

public class WikiPageWriter {
  private ImportsPrinter m_importsPrinter;
  
  public WikiPageWriter(ImportsPrinter importsPrinter) {
    m_importsPrinter = importsPrinter;
  }

  
  void savePage(Page page, PrintStream ostream) throws IOException {
    m_importsPrinter.printImports(page, ostream);
    ostream.append(PageUtils.pageToString(page));
  }
  
  public void savePage(String path, Page page) throws IOException {
    File file = new File(path);
    if (!file.exists()) {
      File dir = new File(file.getParent());
      dir.mkdirs();
      file.createNewFile();
    }

    FileOutputStream stream = null;
    try {
      stream = new FileOutputStream(file);
      savePage(page, new PrintStream(stream));
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
  }
}
